package com.example.oms.service;

import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.*;

import java.util.HashMap;
/**
 * @Author 杨洪波
 * @Date 2024/8/5 23:06
 * @注释
 */

/**
 * 得到信息
 */
@Slf4j
@Service
public class WebSocketService implements WebSocketHandler {
    /**
     * 建立连接
     * @param session
     * @throws Exception
     */
    HashMap<String, WebSocketSession> userToSession=new HashMap<>();
    HashMap<WebSocketSession,String>sessionToUser=new HashMap<>();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        String userid=session.getUri().toString().split("userid=")[1];
        if(!StringUtil.isNullOrEmpty(userid)){
            userToSession.put(userid,session);
        }
    }

    /**
     * 获取信息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

    }

    /**
     * 断开连接
     * @param session
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        userToSession.remove(sessionToUser.get(session));
        sessionToUser.remove(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    public void sendMessage(String deptName,String doctorName,WebSocketSession session){
        try {
            session.sendMessage(new TextMessage(deptName + "-" + doctorName));
        }catch (Exception e){

        }
    }

}

